﻿using PlcLib;
using PlcLib.Mvvm;
using PLC通讯框架开发课程.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace PLC通讯框架开发课程.ViewModel
{
    internal class MainViewModel : ObservableObject
    {
        /// <summary>
        /// 属性才可以绑定到XAML
        /// </summary>
        public OrmonPlc OrmonPlc { get; set; } = new OrmonPlc();

        private ObservableCollection<Message> messageList = new ObservableCollection<Message>();
        public ObservableCollection<Message> MessageList
        {
            get { return messageList; }
            set { messageList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<Message> byteList = new ObservableCollection<Message>();
        public ObservableCollection<Message> ByteList
        {
            get { return byteList; }
            set { byteList = value; RaisePropertyChanged(); }
        }

        public MainViewModel()
        {
            OrmonPlc.OnError += OrmonPlc_OnMessage;
            OrmonPlc.OnMessage += OrmonPlc_OnMessage;
            OrmonPlc.OnSend += OrmonPlc_OnSend;
            OrmonPlc.OnReceived += OrmonPlc_OnReceived;
        }

        private void OrmonPlc_OnReceived(object arg1, CommunicationLib.Model.DataPackage package)
        {
            Message message = new Message();
            message.DateTime = package.ReceiveTime;
            message.Content = "接收:" + package.ReceiveBufferToString;
            System.Windows.Application.Current.Dispatcher.Invoke(() => ByteList.Insert(0, message));
        }

        private void OrmonPlc_OnSend(object arg1, CommunicationLib.Model.DataPackage package)
        {
            Message message = new Message();
            message.DateTime = package.SendTime;
            message.Content = "下发:" + package.SendBufferToString;
            System.Windows.Application.Current.Dispatcher.Invoke(() => ByteList.Insert(0, message));
        }

        private void OrmonPlc_OnMessage(object sender, PlcLib.Model.PlcEventArgs arg)
        {
            Message message = new Message();
            message.DateTime = DateTime.Now;
            message.Content = arg.Message;
            System.Windows.Application.Current.Dispatcher.Invoke(() => MessageList.Insert(0,message));
        }

       
    }
}
